package com.quectel.cms.controller.room;


import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.room.GroupRentingRoomConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.household.dto.HouseholdRoomDto;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageFloorService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-18 14:41:47
 */
@RestController
@RequestMapping("groupRentingRoom")
@Tag(name = "GroupRentingRoomController", description = "群租房相关 api")
public class GroupRentingRoomController extends BaseController {

    @DubboReference
    private VillageRoomService villageRoomService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageFloorService villageFloorService;
    @DubboReference
    private HouseholdRoomService householdRoomService;

    /**
     * 导出房屋信息为excel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "groupRentingRoom:exportExcel")
    @Log(express = "导出群租房信息")
    @Operation(summary = "导出群租房信息为excel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse resp) {
        Request request = Request.configParamsNotPage(params);
        request.put(GroupRentingRoomConstants.TAG_KEYS, Collections.singletonList(GroupRentingRoomConstants.TagsEnum.GROUP_RENTING_ROOM.getType()));

        super.fillAuthorityData(params);

        List<VillageRoomDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<VillageRoomDto> list = villageRoomService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "所属楼栋", "所属楼层", "房屋名称", "房屋户型", "房屋面积", "居住人数", "业主姓名", "业主电话"};
        List<String[]> dataList = new ArrayList<>();
        for (VillageRoomDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getBuildingName();
            item[2] = data.getFloorName();
            item[3] = data.getName();
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.ROOM_TYPE, data.getRoomNature() + "");
            item[5] = data.getRoomArea() != null ? data.getRoomArea().toPlainString() : null;
            item[6] = data.getPeopleCount() + "";
            item[7] = data.getOwnerName();
            item[8] = data.getOwnerMobile();
            dataList.add(item);
        }
        POIUtils.exportExcel(resp, "群租房信息", headers, dataList, "群租房信息");
    }

    /**
     * 根据参数分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "groupRentingRoom:list")
    @Operation(summary = "根据参数分页查询小区房屋列表")
    public Response<Page<VillageRoomDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        request.put(GroupRentingRoomConstants.TAG_KEYS, Collections.singletonList(GroupRentingRoomConstants.TagsEnum.GROUP_RENTING_ROOM.getType()));

        super.fillAuthorityData(request.getParams());
        int total = villageRoomService.queryTotal(request.getParams());

        List<VillageRoomDto> list = null;
        if (total > 0) {
            list = villageRoomService.queryList(request.getParams());
            for (VillageRoomDto villageRoomDto : list) {
                List<HouseholdRoomDto> householdRoomDtos = householdRoomService.selectByRoomId(villageRoomDto.getId());
                villageRoomDto.setPeopleCount(householdRoomDtos.size());
            }
        } else {
            list = new ArrayList<>();
        }

        Page<VillageRoomDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageRoomDto>>ok().wrap(page);
    }

    /**
     * 移除，标记为非群租房
     */
    @PostMapping("remove")
    @RequirePermissions(values = "groupRentingRoom:remove")
    @Operation(summary = "移除，标记为非群租房")
    public Response<Object> remove(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (villageRoomService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        List<VillageRoomDto> updateDtos = new ArrayList<>();
        for (Long id : ids) {
            VillageRoomDto villageRoomDto = villageRoomService.selectCacheById(id);
            if (villageRoomDto == null) {
                continue;
            }
            String tags = villageRoomDto.getTags();
            if (StringUtils.isBlank(tags)) {
                continue;
            }
            HashMap<String, Object> parse = JacksonUtils.parse(tags, new TypeReference<HashMap<String, Object>>(){});
            parse.remove(GroupRentingRoomConstants.TagsEnum.GROUP_RENTING_ROOM.getType().toString());

            VillageRoomDto updateDto = new VillageRoomDto();
            updateDto.setId(id);
            updateDto.setTags(JacksonUtils.toJsonString(parse));
            updateDtos.add(updateDto);
        }

        villageRoomService.updateBatch(updateDtos);

        return Response.ok();
    }
}
